package com.bt.lms.ui.page.sys.major.action;

import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.SysBizTypeConstant;
import com.bt.lms.entity.Major;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.sys.major.PageCompile;
import com.bt.lms.ui.page.sys.utils.ArrayUtils;
import com.bt.lms.ui.page.sys.utils.NetWorkUtils;
import com.bt.lms.ui.vo.PageSkipInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.page.sys.ServerInfo;
import com.bt.lms.ui.page.sys.utils.Encode;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

/**
 * 保存按钮事件（编辑专业界面）
 */
public class MCSaveBtnAction implements EventHandler<ActionEvent> {

    /**
     * 界面跳转信息
     */
    private final PageSkipInfo pageSkipInfo;

    /**
     * 源专业
     */
    private final Major srcMajor;

    /**
     * 构建事件
     *
     * @param pageSkipInfo 界面跳转信息
     * @param srcMajor     源专业信息
     */
    public MCSaveBtnAction(PageSkipInfo pageSkipInfo, Major srcMajor) {
        this.pageSkipInfo = pageSkipInfo;
        this.srcMajor = srcMajor;
    }

    /**
     * 方法实现
     *
     * @param event the event which occurred
     */
    @Override
    public void handle(ActionEvent event) {

        //1.获取用户输入
        Major major = getInPut();
        //2.验证用户输入
        String hint = verifyInPut(major);
        //3.组装网络消息包
        if (hint == null) {
            ReqMsg reqMsg = Encode.encodeToMsg(major, SysBizTypeConstant.MAJOR_COMPILE);
            byte[] bytes = reqMsg.toBytes();
            //4.组网
            Socket socket = packageNet();
            OutputStream out;
            try {
                out = socket.getOutputStream();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //5.发送
            boolean b = sendMesNet(out, bytes);
            if (b) {
                try {
                    InputStream in = socket.getInputStream();
                    //6.接受响应
                    List<byte[]> bufS = NetWorkUtils.receive(in);
                    //6.1 处理结果
                    byte[] respBytes = ArrayUtils.joinBytes(bufS);
                    //6.2 转消息
                    RespMsg respMsg = RespMsg.toRespMsg(respBytes);
                    //6.3 比较状态
                    short status = respMsg.getStatus();
                    if (status == RespMsg.NETWORK_STATUS_NORMAL) {
                        //资源关闭
                        in.close();
                        out.close();
                        socket.close();
                        //成功发送，程序结束
                        succeed();//保存成功
                    } else {
                        fail("响应失败，请稍候重试。");
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            } else
                fail("保存失败，请稍候重试。");//失败提示
        } else {
            fail(hint);//失败提示
        }
    }

    /**
     * 获取用户输入
     *
     * @return 用户输入
     */
    private Major getInPut() {

        //要返回的对象
        Major major = new Major();
        //维护id
        major.setId(srcMajor.getId());
        //界面对象
        Pane pane = pageSkipInfo.getPane();
        //专业名称
        TextField nameTF = (TextField) pane.lookup("#" + PageCompile.NAME_TF);
        String name = nameTF.getText().trim();
        major.setName(name);
        //专业说明
        TextArea describeTF = (TextArea) pane.lookup("#" + PageCompile.DESCRIBE_TA);
        try {
            String describe = describeTF.getText().trim();
            major.setDetails(describe);
        } catch (Exception e) {
            major.setDetails(null);
        }
        return major;
    }

    /**
     * 验证用户输入
     *
     * @param major 用户输入
     * @return 验证结果
     */
    private String verifyInPut(Major major) {

        //提示文本
        String hint = "";
        //专业名称 必填 文本 15以内
        String name = major.getName();
        int nameLen = name.length();
        if ("".equals(name))
            hint += "名称未填，请输入名称。\n\t";
        else if (nameLen > 15)
            hint += "名称长度不合适，请输入15以下的中文、字母、数字。\n\t";

        //专业说明 非必填 文本 大
        String describe = major.getDetails();
        if (describe != null){
            int describeLen = describe.length();

            if (!"".equals(describe))
                if (describeLen > 65535)
                    hint += "专业说明过大，最大65535。\n\t";
        }

        return "".equals(hint) ? null : hint;

    }

    /**
     * 组网
     *
     * @return 网
     */
    private Socket packageNet() {
        String ip = ServerInfo.IP;
        Integer port = ServerInfo.PORT;

        try {
            return new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送
     *
     * @param out   输出流
     * @param bytes 要发送的数据
     * @return 发送结果
     */
    private boolean sendMesNet(OutputStream out, byte[] bytes) {

        //发送网络
        try {
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 失败提示
     *
     * @param hint 提示内容
     */
    private void fail(String hint) {

        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("失败");
        alert.setHeaderText(null);
        alert.setContentText(hint);
        alert.showAndWait();

    }

    /**
     * 结束方法（保存成功）
     */
    private void succeed() {
        //提示 + 跳转
        //保存提示
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("成功");//头部提示
        alert.setHeaderText(null);//清除固有提示
        alert.setContentText("保存成功");//提示文本
        alert.showAndWait();//显示
        //界面跳转
        NetWorkUtils.reqMajorPagingPage(pageSkipInfo, new Page<>());
    }
}
